<?php

/**
 * nmp版后台入口接口
 * Class CustomerWeixinProfileAction
 * @author lsp
 */
class CustomerWeixinProfileAction extends Action
{
    public function _initialize()
    {

        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }
        $this->cid     = Session::$user["customerId"];
        $this->userId  = Session::$user["id"];
        Session::switchCustomer(0);
        /**
         * 这里通过id(cid)查询wx_customer信息
         * LLyeap_wx_customer修改
         */
//        $this->customer_db = D('Customer');
        $this->ind_media_info_db = D('ind_media_info');
        $this->customer_weixin_profile_db = D('CustomerWeixinProfile');
        $this->customer_weibo_profile_db = D('CustomerWeiboProfile');
        $this->customer_toutiao_profile_db = D('CustomerToutiaoProfile');
        $this->customer_user_db = D('CustomerUser');

        $this->third_platform_db = D('ThirdPlatform');
        Session::switchCustomer($this->cid);
        // $this->wechatThirdPlatform = new WechatThirdPlatform();
    }

    /**
     * 获得授权平台的第三方信息
     *
     * @param int $cid      那个账号下
     * @param int $mediaId  那个自媒体平台, 不传则使用默认账号ind_media_info里各cid下所有自媒体账号中有一个isDefault为1的默认账号
     */
    public function get_customer_weixin_profile_detail($cid = 0, $mediaId = 0)
    {
        $result = $map = array();
        $result['code'] = 0;

        $cid     = ($cid > 0) ? $cid : $this->cid;
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['a.cid' => $cid, 'a.id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['a.cid' => $cid, 'a.isDefault' => 1];
        }
        /***** LLyeap_delete *****/
//        if ($cid > 0) {
//            $map['a.id'] = $cid;
//        } else {
//            $map['a.id'] = $this->cid;
//        }
        /*****  *****/
        // $this->get_authorization_base_info($cid);
        Session::switchCustomer(0);

        $indMediaType = $this->ind_media_info_db->alias('a')
            ->where($where_info)
            ->getField('type');

        if ($indMediaType == 1) {     // 微信
            $detail = $this->ind_media_info_db->alias('a')
                ->field('a.cid as customer_id,a.*,b.*,cu.brandName,cu.brandLogoUrl')
                ->join('left join ' . C('DB_PREFIX') . 'customer_weixin_profile b ON a.id = b.mediaId')
                ->join('left join ' . C('DB_PREFIX') . 'customer cu ON a.cid = cu.id')
                ->where($where_info)
                ->find();
        } else if ($indMediaType == 2) {    // 微博
            $detail = $this->ind_media_info_db->alias('a')
                ->field('a.cid as customer_id,a.*,b.*,cu.brandName,cu.brandLogoUrl')
                ->join('left join ' . C('DB_PREFIX') . 'customer_weibo_profile b ON a.id = b.mediaId')
                ->join('left join ' . C('DB_PREFIX') . 'customer cu ON a.cid = cu.id')
                ->where($where_info)
                ->find();
        } else if ($indMediaType == 3) {    // 头条号
            $detail = $this->ind_media_info_db->alias('a')
                ->field('a.cid as customer_id,a.*,b.*,cu.brandName,cu.brandLogoUrl')
                ->join('left join ' . C('DB_PREFIX') . 'customer_toutiao_profile b ON a.id = b.mediaId')
                ->join('left join ' . C('DB_PREFIX') . 'customer cu ON a.cid = cu.id')
                ->where($where_info)
                ->find();
        }

        /***** LLyeap_delete *****/
//        $detail = $this->customer_db->alias('a')
//            ->field('a.id as customer_id,a.*,b.*')
//            ->join('left join ' . C('DB_PREFIX') . 'customer_weixin_profile b on a.id = b.cid')
//            ->where($map)
//            ->find();
        /*****  *****/

        if ($detail) {
            if ($detail['mode'] == 1 && $detail['grantStatus'] == 1) {
                $detail['grantStatus'] = 1;
            }
            // 为确保准确, 这里使用id和cid共同筛选
            $customer_user_map = array();
            $customer_user_map['id']         = $this->userId;
            $customer_user_map['customerId'] = $this->cid;
            $result['customer_user_info'] = $this->customer_user_db
                ->field('registered,password', true)
                ->where($customer_user_map)
                ->find();

            $detail['third_platform_appid'] = $detail['third_platform_appid'] ? $detail['third_platform_appid'] : '';
            $detail['appid'] = $detail['appid'] ? $detail['appid'] : '';

            if ($indMediaType == 1) {   // 微信
                $detail['auth_url'] = WechatThirdPlatform::get_oauth_url($detail['third_platform_appid'], '');
            } else if ($indMediaType == 2) {    // 微博
                $detail['auth_url'] = WeiboApi::getWeiboAuthorizeUrl($detail['third_platform_appid'], $mediaId);
            } else if ($indMediaType == 3) {    // 头条号
                $detail['auth_url'] = ToutiaoApi::getToutiaoAuthorizeUrl($detail['third_platform_appid'],  $mediaId);
            }

            $result['code'] = 1;
            $result['detail'] = $detail;

//            // 调用接口方法, 获得该用户的权限modules
//            $auth_modules = R('Module/getAllRoles', ['nmp', TRUE]);
//            $auth_tree    = $this->format_auth_tree($auth_modules);
//            $result['auth_tree'] = empty($auth_tree) ? [] : $auth_tree;

        } else {
            $result['info'] = '不存在用户信息';
        }
        Output::instance()->object($result);

    }

    /**
     * 刷新第三方信息
     *
     * @param int $cid
     * @param int $mediaId
     */
    public function get_customer_weixin_profile_detail_refresh($cid = 0, $mediaId = 0)
    {
        $result = $map = array();
        $result['code'] = 0;

        $cid     = ($cid > 0) ? $cid : $this->cid;
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['a.cid' => $cid, 'a.id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['a.cid' => $cid, 'a.isDefault' => 1];
        }
        /***** LLyeap_delete *****/
//        if ($cid > 0) {
//            $map['a.id'] = $cid;
//        } else {
//            $map['a.id'] = $this->cid;
//        }
         /*****  *****/
        $indMediaType = $this->ind_media_info_db->alias('a')
            ->where($where_info)
            ->getField('type');


        if ($indMediaType == 1) {   // 微信
            $this->get_authorization_base_info($cid, $mediaId);

            Session::switchCustomer(0);
            $detail = $this->ind_media_info_db->alias('a')
                ->field('a.cid as customer_id,a.*,b.*')
                ->join('left join ' . C('DB_PREFIX') . 'customer_weixin_profile b ON a.id = b.mediaId')
                ->where($where_info)
                ->find();
        } else if ($indMediaType == 2) {    // 微博
            // TODO: 微博授权信息刷新
            $this->get_wb_authorization_base_info($cid, $mediaId);

            Session::switchCustomer(0);
            $detail = $this->ind_media_info_db->alias('a')
                ->field('a.cid as customer_id,a.*,b.*')
                ->join('left join ' . C('DB_PREFIX') . 'customer_weibo_profile b ON a.id = b.mediaId')
                ->where($where_info)
                ->find();
        } else if ($indMediaType == 3) {    // 头条号
            $this->get_tt_authorization_base_info($cid, $mediaId);

            Session::switchCustomer(0);
            $detail = $this->ind_media_info_db->alias('a')
                ->field('a.cid as customer_id,a.*,b.*')
                ->join('left join ' . C('DB_PREFIX') . 'customer_toutiao_profile b ON a.id = b.mediaId')
                ->where($where_info)
                ->find();
        }

         /***** LLyeap_delete *****/
//        $detail = $this->customer_db->alias('a')
//            ->field('a.id as customer_id,a.*,b.*')
//            ->join('left join ' . C('DB_PREFIX') . 'customer_weixin_profile b on a.id = b.cid')
//            ->where($map)
//            ->find();
         /*****  *****/

        if ($detail) {
            if ($detail['mode'] == 1 && $detail['grantStatus'] == 1) {
                $detail['grantStatus'] = 1;
            }
            $customer_user_map = array();
            $customer_user_map['customerId'] = $this->cid;
//            $result['customer_user_info'] = $this->customer_user_db->field('id,registered,password', true)->where($customer_user_map)->find();
            $detail['third_platform_appid'] = $detail['third_platform_appid'] ? $detail['third_platform_appid'] : '';
//            $detail['auth_url'] = WechatThirdPlatform::get_oauth_url($detail['third_platform_appid'], '');
            $result['code'] = 1;
            $result['detail'] = $detail;

            // 调用接口方法, 获得该用户的权限modules
            // $auth_modules = R('Module/getAllRoles', ['nmp', TRUE]);
            // $auth_tree    = $this->format_auth_tree($auth_modules);
            // $result['auth_tree'] = empty($auth_tree) ? [] : $auth_tree;

        } else {
            $result['info'] = '不存在用户信息';
        }
        Output::instance()->object($result);

    }

    /**
     * 微信刷新授权详细信息
     *
     * @param int $cid
     * @param int $mediaId
     */
    public function get_authorization_base_info($cid = 0, $mediaId = 0)
    {
        $cid     = ($cid > 0) ? $cid : $this->cid;
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['a.cid' => $cid, 'a.id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['a.cid' => $cid, 'a.isDefault' => 1];
        }
        /***** LLyeap_delete *****/
//        $map = array();
//        if ($cid > 0) {
//            $map['a.id'] = $cid;
//        } else {
//            $map['a.id'] = $this->cid;
//        }
        /*****  *****/

        $where_info['b.grantStatus'] = 1;
        Session::switchCustomer(0);

        $customer_info = $this->ind_media_info_db->alias('a')
            ->field('a.cid as cid, a.third_platform_appid, a.appid, b.id as customer_weixin_profile_id')
            ->join('left join ' . C('DB_PREFIX') . 'customer_weixin_profile b ON a.id = b.mediaId')
            ->where($where_info)
            ->find();
        /***** LLyeap_delete *****/
//        $customer_info = $this->customer_db->alias('a')
//            ->field('a.id as cid,a.third_platform_appid,a.appid,b.id as customer_weixin_profile_id')
//            ->join('inner join ' . C('DB_PREFIX') . 'customer_weixin_profile b on a.id = b.cid')
//            ->where($map)
//            ->find();
        /*****  *****/

        if ($customer_info) {
            $cid = $customer_info['cid'];
            $component_appid = $customer_info['third_platform_appid'];
            $authorizer_appid = $customer_info['appid'];
            $authorizer_info_base = WechatThirdPlatform::get_authorization_base_info($component_appid, $authorizer_appid);
            if ($authorizer_info_base && $authorizer_info_base->errcode == 0) {
                $authorizer_info = $authorizer_info_base->authorizer_info;
                $authorization_info_base = $authorizer_info_base->authorization_info;
                $func_info_array = array();
                $func_info = $authorization_info_base->func_info;
                foreach ($func_info as $key => $value) {
                    $func_info_array[$key] = $value->funcscope_category->id;
                }
                $func_info_str = implode(',', $func_info_array);
                $customer_weixin_profile_id = $customer_info['customer_weixin_profile_id'];
                $customer_weixin_profile_data = array();
                $customer_weixin_profile_data['cid'] = $customer_info['cid'];
                // $this->customer_user_db->where('customerId=' . $cid)->setField('fullName', $authorizer_info->nick_name);
                $customer_weixin_profile_data['nick_name'] = $authorizer_info->nick_name;

                $customer_weixin_profile_data['head_img'] = $authorizer_info->head_img;
                $customer_weixin_profile_data['service_type_info'] = $authorizer_info->service_type_info->id;
                $customer_weixin_profile_data['verify_type_info'] = $authorizer_info->verify_type_info->id;
                $customer_weixin_profile_data['user_name'] = $authorizer_info->user_name;
                $customer_weixin_profile_data['principal_name'] = $authorizer_info->principal_name;
                $business_info = $authorizer_info->business_info;
                $business_info = json_encode($business_info);
                Log::write('business_info:' . $business_info . 'length:' . strlen($business_info));
                $customer_weixin_profile_data['business_info'] = $business_info;

                $customer_weixin_profile_data['alias'] = $authorizer_info->alias;

                $customer_weixin_profile_data['alias'] = $authorizer_info->alias;
                $customer_weixin_profile_data['func_info'] = $func_info_str;
                $customer_weixin_profile_data['grantTime'] = date('Y-m-d H:i:s');
                $customer_weixin_profile_data['grantStatus'] = 1;
                $service_open_status = array();
                $service_open_status['location_report'] = WechatThirdPlatform::get_authorizer_set($component_appid, $authorizer_appid, 'location_report')->option_value;
                $service_open_status['voice_recognize'] = WechatThirdPlatform::get_authorizer_set($component_appid, $authorizer_appid, 'voice_recognize')->option_value;
                $service_open_status['customer_service'] = WechatThirdPlatform::get_authorizer_set($component_appid, $authorizer_appid, 'customer_service')->option_value;
                $customer_weixin_profile_data['service_open_status'] = json_encode($service_open_status);
                if ($customer_weixin_profile_id > 0) {
                    $customer_weixin_profile_map = array();
                    $customer_weixin_profile_map['id'] = $customer_weixin_profile_id;
                    $customer_weixin_profile_result = $this->customer_weixin_profile_db->where($customer_weixin_profile_map)->save($customer_weixin_profile_data);
                } else {
                    $customer_weixin_profile_result = $this->customer_weixin_profile_db->add($customer_weixin_profile_data);
                }
                Log::write('customer_sql:' . $this->ind_media_info_db->_sql());
                Log::write('customer_weixin_profile_sql:' . $this->customer_weixin_profile_db->_sql());

            }
        }
    }

    /**
     * 微博刷新授权详细信息
     *
     * @param int $cid
     * @param int $mediaId
     */
    public function get_wb_authorization_base_info($cid = 0, $mediaId = 0)
    {
        $cid     = ($cid > 0) ? $cid : $this->cid;
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['a.cid' => $cid, 'a.id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['a.cid' => $cid, 'a.isDefault' => 1];
        }

        $where_info['b.grantStatus'] = 1;
        Session::switchCustomer(0);

        $customer_info = $this->ind_media_info_db->alias('a')
            ->field('a.cid as cid, a.third_platform_appid, a.appid, b.id as customer_weibo_profile_id, b.uid')
            ->join('left join ' . C('DB_PREFIX') . 'customer_weibo_profile b ON a.id = b.mediaId')
            ->where($where_info)
            ->find();

        if ($customer_info) {
            // 先拿到clentkey 和 token
            // 在拿info
            $obj_token = WeiboApi::getWeiboAccessToken($mediaId);
            $accessToken = null;
            $uid = $customer_info['uid'];   // 微博的uid
            if ($obj_token['code'] == 0) {  // 获取token没问题
                $accessToken = $obj_token['data'];
            } else {    // 授权token有问题
                \Log::write('CustomerWeixinPorfile::get_wb_authorization_base_info() => 微博授权的token有问题');
                return;
            }
            $newInfo = WeiboApi::getThirdWeiboInfo($accessToken, $uid);

            if ($newInfo) {
                $data['idstr']              = $newInfo['idstr'];
                $data['screen_name']        = $newInfo['screen_name'];
                $data['name']               = $newInfo['name'];
                $data['province']           = $newInfo['province'];
                $data['city']               = $newInfo['city'];
                $data['location']           = $newInfo['location'];
                $data['description']        = $newInfo['description'];
                $data['url']                = $newInfo['url'];
                $data['profile_image_url']  = $newInfo['profile_image_url'];
                $data['profile_url']        = $newInfo['profile_url'];
                $data['domain']             = $newInfo['domain'];
                $data['weihao']             = $newInfo['weihao'];
                $data['gender']             = $newInfo['gender'];
                $data['followers_count']    = $newInfo['followers_count'];
                $data['friends_count']      = $newInfo['friends_count'];
                $data['statuses_count']     = $newInfo['statuses_count'];
                $data['favourites_count']   = $newInfo['favourites_count'];
                $data['created_at']         = $newInfo['created_at'];
                $data['following']          = $newInfo['following'];
                $data['allow_all_act_msg']  = $newInfo['allow_all_act_msg'];
                $data['gen_enabled']        = $newInfo['gen_enabled'];
                $data['verified']           = $newInfo['verified'];
                $data['verified_type']      = $newInfo['verified_type'];
                $data['remark']             = $newInfo['remark'];
                $data['status']             = $newInfo['status'];
                $data['allow_all_comment']  = $newInfo['allow_all_comment'];
                $data['avatar_large']       = $newInfo['avatar_large'];
                $data['avatar_hd']          = $newInfo['avatar_hd'];
                $data['verified_reason']    = $newInfo['verified_reason'];
                $data['follow_me']          = $newInfo['follow_me'];
                $data['online_status']      = $newInfo['online_status'];
                $data['bi_followers_count'] = $newInfo['bi_followers_count'];
                $data['lang']               = $newInfo['lang'];

                $customer_weibo_profile_id = $customer_info['customer_weibo_profile_id'];
                if ($customer_weibo_profile_id > 0) {
                    $customer_weibo_profile_map = array();
                    $customer_weibo_profile_map['id'] = $customer_weibo_profile_id;
                    $customer_toutiao_profile_result = $this->customer_weibo_profile_db->where($customer_weibo_profile_map)->save($data);
                } else {
                    $data['cid']        = $cid;
                    $data['mediaId']    = $mediaId;
                    $data['grantTime']  = date('Y-m-d H:i:s');
                    $data['grantStatus']= 1;
                    $customer_toutiao_profile_result = $this->customer_weibo_profile_db->add($data);
                }
            }
        }
    }

    /**
     * 头条刷新授权详细信息
     *
     * @param int $cid
     * @param int $mediaId
     */
    public function get_tt_authorization_base_info($cid = 0, $mediaId = 0)
    {
        $cid     = ($cid > 0) ? $cid : $this->cid;
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['a.cid' => $cid, 'a.id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['a.cid' => $cid, 'a.isDefault' => 1];
        }

        $where_info['b.grantStatus'] = 1;
        Session::switchCustomer(0);

        $customer_info = $this->ind_media_info_db->alias('a')
            ->field('a.cid as cid, a.third_platform_appid, a.appid, b.id as customer_toutiao_profile_id, b.uid')
            ->join('left join ' . C('DB_PREFIX') . 'customer_toutiao_profile b ON a.id = b.mediaId')
            ->where($where_info)
            ->find();

        if ($customer_info) {
            // 先拿到clentkey 和 token
            // 在拿info
            $obj_token = ToutiaoApi::getToutiaoAccessToken($mediaId);
            $accessToken = null;
            $clientKey = $customer_info['third_platform_appid'];   // 头条的client_key
            if ($obj_token['code'] == 0) {  // 获取token没问题
                $accessToken = $obj_token['data'];
            } else {    // 授权token有问题
                \Log::write('CustomerWeixinPorfile::get_tt_authorization_base_info() => 头条授权的token有问题');
                return;
            }
            $newInfo = ToutiaoApi::getThirdToutiaoInfo($clientKey, $accessToken);

            if ($newInfo) {
                $data = [
                    'screen_name'   => $newInfo['screen_name'],
                    'open_id'       => $newInfo['open_id'],
                    'uid_type'      => $newInfo['uid_type'],
                    'uid'           => $newInfo['uid'],
                    'media_id'      => $newInfo['media_id'],
                    'description'   => $newInfo['description'],
                    'extra'         => $newInfo['extra'],
                    'avatar_url'    => $newInfo['avatar_url'],
                    'media_name'    => $newInfo['media_name'],
                    'user_verified' => $newInfo['user_verified'],
                ];

                $customer_toutiao_profile_id = $customer_info['customer_toutiao_profile_id'];
                if ($customer_toutiao_profile_id > 0) {
                    $customer_toutiao_profile_map = array();
                    $customer_toutiao_profile_map['id'] = $customer_toutiao_profile_id;
                    $customer_toutiao_profile_result = $this->customer_toutiao_profile_db->where($customer_toutiao_profile_map)->save($data);
                } else {
                    $data['cid']        = $cid;
                    $data['mediaId']    = $mediaId;
                    $data['grantTime']  = date('Y-m-d H:i:s');
                    $data['grantStatus']= 1;
                    $customer_toutiao_profile_result = $this->customer_toutiao_profile_db->add($data);
                }
            }

        }
    }

    /**
     * 获得授权url
     *
     * @param     $url
     * @param int $mediaId  对那个自媒体进行授权
     */
    public function get_oauth_url($url='', $mediaId = 0)
    {
        if ($mediaId > 0) { // 如果传了参数$mediaId, 则通过id来筛选
            $where_info = ['cid' => $this->cid, 'id' => $mediaId];
        } else {            // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['cid' => $this->cid, 'isDefault' => 1];
        }
        $ind_media_info = $this->ind_media_info_db->where($where_info)->field('id, cid, third_platform_appid')->find();

        $mediaId = $ind_media_info['id'];
        $cid = $ind_media_info['cid'];
        $component_appid = $ind_media_info['third_platform_appid'];
        $result = [
            'code'      => 1,
            'auth_host' => C('AUTH_SERVER_HOST') . 'Callback/spons_auth.json',
            'url'       => $url,
            'mediaId'   => $mediaId,
            'cid'       => $cid,
            'third_platform_appid'  => $component_appid
        ];
        Output::instance()->object($result);


        /***** LLyeap_delete *****/
//        $component_appid = $this->customer_db->where('id=' . $this->cid)->getField('third_platform_appid');
        /*****  *****/

//        $oauth_url = WechatThirdPlatform::get_oauth_url($component_appid, $url, $mediaId);
//        $result = array();
//        $result['code'] = 1;
//        $result['auth_url'] = $oauth_url;
//        Output::instance()->object($result);
    }

    public function update_service_open_status($component_appid, $authorizer_appid, $location_report = NULL, $voice_recognize = NULL, $customer_service = NULL)
    {

        if ($location_report != NULL) {
            $res = WechatThirdPlatform::set_authorizer_option($component_appid, $authorizer_appid, 'location_report', $location_report);
            $option_name = 'location_report';
            $option_value = $location_report;
        }
        if ($voice_recognize != NULL) {

            $res = WechatThirdPlatform::set_authorizer_option($component_appid, $authorizer_appid, 'voice_recognize', $voice_recognize);
            $option_name = 'voice_recognize';
            $option_value = $voice_recognize;
        }
        if ($customer_service != NULL) {
            $res = WechatThirdPlatform::set_authorizer_option($component_appid, $authorizer_appid, 'customer_service', $customer_service);
            $option_name = 'customer_service';
            $option_value = $customer_service;
        }

        $result = array();
        $result['code'] = 0;
        if ($res) {
            if ($res->errcode == 0) {
                $map = array();
                $map['cid'] = $this->cid;
                $info = $this->customer_weixin_profile_db->where($map)->find();
                if ($info) {
                    $service_open_status = $info['service_open_status'];
                    if ($service_open_status) {
                        $service_open_status_array = json_decode($service_open_status, true);
                        $service_open_status_array[$option_name] = $option_value;
                    } else {
                        $service_open_status_array = array();
                        $service_open_status_array[$option_name] = $option_value;
                    }

                    $service_open_status = json_encode($service_open_status_array);
                    $result['service_open_status'] = $service_open_status;
                    $save_data = array();
                    $save_data['service_open_status'] = $service_open_status;
                    $update_result = $this->customer_weixin_profile_db->where($map)->save($save_data);
                    log::write('slq:' . $this->customer_weixin_profile_db->_sql());
                    $sql = $this->customer_weixin_profile_db->_sql();
                    if ($update_result) {
                        $result['code'] = 1;
                    } else {
                        $result['sql'] = $sql;
                        $result['info'] = '本地更新数据库失败';
                    }


                } else {
                    $result['info'] = '此账号的授权信息不存在';
                }

            } else {
                $result['info'] = $res->errmsg ? $res->errmsg : "微信调用失败";
            }
        } else {
            $result['info'] = '接口调用错误';
        }
        Output::instance()->object($result);
    }


    /**
     * 获取授权第三方平台信息, 并且, 超管在为某个用户设置授权第三方平台需要知道目前已设置的第三方授权平台
     * 超管设置
     *
     * @param $cid      wx_customer表id/wx_customer_user表customerId, 哪个用户
     */
    public function get_all_third_platform($cid, $mediaId = 0)
    {
        /** 0. 判断是不是超级管理员 */
        $isAdmin = Session::isAdmin();
        if (!$isAdmin) {
            Output::instance()->resultCode(code_user_priv_invalid);
            exit();
        }

        // 查询第三方平台数据返回
        $thirdPlatforms = $this->third_platform_db->field('appid, name')->select();
        // 有一个默认的第三方平台, 这个上线正式平台时需要修改一下名称"默认第三方平台"
        // 默认第三方平台起一个统一的名字"默认第三方平台", 这样, 在数据库里第三方默认平台的名称改变时, 不需要修改代码
        foreach ($thirdPlatforms as $thirdPlatform_index => $thirdPlatform) {
            if ($thirdPlatform['name'] == 'default') {
                $thirdPlatforms[$thirdPlatform_index]['name'] = '默认第三方平台';
                break;
            }
        }

        // 查询账号已设置的第三方平台情况
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['cid' => $cid, 'id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['cid' => $cid, 'isDefault' => 1];
        }
        $third_platform_appid = $this->ind_media_info_db->where($where_info)->getField('third_platform_appid');
        /***** LLyeap_delete *****/
//        $where['id'] = $cid;
//        $third_platform_appid = $this->customer_db->where($where)->getField('third_platform_appid');
        /*****  *****/

        if (isset($third_platform_appid)) {
            $thirdPlatformWhere['appid'] = $third_platform_appid;
            $third_platform_name = $this->third_platform_db->where($thirdPlatformWhere)->getField('name');
        }

        $result = [
            'code'  => 0,
            'msg'   => '第三方平台获取成功',
            'third_platform'    => $thirdPlatforms,
            'user_third_platform_appid' => (isset($third_platform_appid) && isset($third_platform_name)) ? $third_platform_appid : '',
            'user_third_platform_name'  => isset($third_platform_name) ? (($third_platform_name == 'default') ? '默认第三方平台' : $third_platform_name) : ''
        ];
        Output::instance()->object($result);
    }

    /**
     * 超管设置某个用户的授权第三方平台
     *
     * @param $cid      wx_customer表id/wx_customer_user表customerId
     * @param $appid    要授权给那个公众号
     */
    public function set_user_third_platform($cid, $appid, $mediaId = 0)
    {
        /** 0. 判断是不是超级管理员 */
        $isAdmin = Session::isAdmin();
        if (!$isAdmin) {
            Output::instance()->resultCode(code_user_priv_invalid);
            exit();
        }


        // 修改设置账号需要授权的公众号
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['cid' => $cid, 'id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['cid' => $cid, 'isDefault' => 1];
        }
        $data['third_platform_appid'] = $appid;
        $update_result = $this->ind_media_info_db->where($where_info)->save($data);
        /***** LLyeap_delete *****/
//        $where['id'] = $cid;
//        $data['third_platform_appid'] = $appid;
//        $update_result = $this->customer_db->where($where)->save($data);
        /*****  *****/

        // 结果返回
        if ($update_result !== FALSE) {
            $result = [
                'code'  => 0,
                'msg'   => '设置授权公众号成功!'
            ];
        } else {
            $result = [
                'code'  => 1,
                'msg'   => '设置授权公众号失败,请重试!'
            ];
        }
        Output::instance()->object($result);
    }

    /**
     * 获取登录用户的权限树
     * 在本类的get_customer_weixin_profile_detail方法中也有, 这里独立出来一个, 胡框架升级后会统一整合
     */
    public function get_user_auth_tree()
    {
        // 调用接口方法, 获得该用户的权限modules
        $auth_modules = R('Module/getAllRoles', ['nmp', TRUE]);
        $auth_tree    = $this->format_auth_tree($auth_modules);

        if (empty($auth_tree)) {    // 权限树无数据
            $result['code'] = 1;
            $result['msg'] = '无权限数据';
            $result['auth_tree'] = [];
        } else {    // 权限树获取成功
            $result['code'] = 0;
            $result['msg'] = '权限树获取成功';
            $result['auth_tree'] = $auth_tree;
        }

        Output::instance()->object($result);
    }

    /**
     * 格式化权限树
     *
     * @param $auth_modules
     * @return array
     */
    protected function format_auth_tree($auth_modules)
    {
        $auth_tree = [];
        foreach ($auth_modules as $index => $module) {
            $tree = [
                'id'        => $module['id'],
                'name'      => $module['name'],
                'level'     => 1,
                'parent'    => $module['pid'],
                'path'      => $module['id'],
                'icon'      => $module['iconurl'],
                'url'       => $module['href'],
                'isMenu'    => 1
            ];
            $childs = [];
            foreach ($module['childs'] as $child_index => $child) {
                // 子级菜单在菜单树中不显示
                if ($child['beShow'] == 0) {
                    unset($module['childs'][$child_index]);
                    continue;
                }
                $child_arr = [
                    'id'        => $child['id'],
                    'name'      => $child['name'],
                    'level'     => 2,
                    'parent'    => $child['pid'],
                    'path'      => $child['pid'] . '-' . $child['id'],
                    'icon'      => $child['iconurl'],
                    'url'       => $child['href'],
                    'isMenu'    => $child['beShow'],
                    'children'  => []
                ];
                array_push($childs, $child_arr);
            }
            $tree['children'] = $childs;

            array_push($auth_tree, $tree);
        }

        return $auth_tree;
    }
}